package ferp.android.tasks.local;

import ferp.android.activities.Ferp;
import ferp.android.services.IResolverService2;
import ferp.android.services.ServiceException;
import ferp.android.services.ServiceProxy;
import ferp.core.card.Card;
import ferp.core.game.Game;
import ferp.core.game.Settings;
import ferp.core.game.Trick;
//import ferp.core.state.State;

/**
 * User: olegs
 * Date: 2/3/13 11:12 AM
 */
public class TaskGameStateRestorer extends TaskSerial<Void, ServiceException>
{
  public TaskGameStateRestorer(Ferp ferp, Game game, Settings settings, IResolverService2 service)
  {
    super(ferp);

    this.game = game;
    this.settings = settings;
    this.service = service;
  }

  @Override
  protected void onPreExecute()
  {
    ferp().onGameRestoreStart(game);
  }

  @Override
  protected ServiceException doInBackground(Void... voids)
  {
    try
    {
      // initialize
      ServiceProxy.initialize(service, game, settings);

      // do not continue if cancelled
      if (!isCancelled())
      {
        // go over all the tricks in the game and advance the resolver
        for (int trick : game.trick.list())
          advance(trick);

        // now the current trick (may be incomplete)
        advance(game.trick.current);

        // solve
        ServiceProxy.solve(service);
      }

      return null;
    }
    catch (ServiceException e)
    {
      return e;
    }
  }

  @Override
  protected void doOnPostExecute(ServiceException e)
  {
    // Note: the compatibility with old versions (prior to 38) requires checking the trick size
    //       as the save could happen in any state
    // next state in GIO if trick size < 3, otherwise the last saved state
    if (e == null)
    {
/*
      Log.debug(Log.TAG, "Resume onPostExecute - state=" + game.state().getClass().getSimpleName() + ", trick size: " + Trick.size(game.trick.current));

      if (game.state() != State.gio && Trick.size(game.trick.current) < 3)
      {
        game.options.clear();
        game.set(State.gio);

        Log.debug(Log.TAG, "Resume onPostExecute - state changed to GIO");
      }
*/

      ferp().onGameRestoreEnd(game);
    }
    else
      ferp().exit(e);
  }

  private final Game game;
  private final Settings settings;
  private final IResolverService2 service;

  // advance resolver with cards in trick
  private void advance(int trick) throws ServiceException
  {
    // start temporary trick with talon card only (if any), then add other cards while advancing the resolver
    int t = Trick.reset(trick);

    for (int i = 0; i < Game.PLAYERS; ++i)
    {
      Card card = Trick.card(trick, i);

      if (card != null)
      {
        t = Trick.add(t, Trick.owner(trick, i), card.compressed);

        ServiceProxy.advance(service, i, t);
      }
    }
  }
}
